﻿/**** begin formWatcher ******/
/* 
// NOTE: the trickiest thing about formWatcher is the way it can handle custom success or before submit functions.  Here is an example:

var formWatcher = new jQuery.g.formWatcher();
formWatcher.registerSuccessFunction('form.someForm', function (data) {
    // do whatever you want here, and when <form class="async someForm" ... > is being posted, this will execute
});

*/
jQuery.g.formWatcher = function (options) {

    this.settings = jQuery.extend({
        watchOnlyFor: 'form.watched',
        asyncSelector: 'form.async',
        validateSelector: 'form.validate',
        confirmSelector: 'form.confirm',
        commonInstance: jQuery.g.common.instance,
        customBeforeSubmitFunctions: new Array(),
        customSuccessFunctions: new Array(),
        customErrorFunctions: new Array()
    }, options);

    this.init();
};
jQuery.g.formWatcher.instance = null;
jQuery.g.formWatcher.prototype.settings = null;
jQuery.g.formWatcher.prototype.registerBeforeSubmitFunction = function (formSelector, theFunction) {
    this.settings.customBeforeSubmitFunctions[formSelector] = theFunction;
};
jQuery.g.formWatcher.prototype.registerSuccessFunction = function (formSelector, theFunction) {
    this.settings.customSuccessFunctions[formSelector] = theFunction;
};
jQuery.g.formWatcher.prototype.registerErrorFunction = function (formSelector, theFunction) {
    this.settings.customErrorFunctions[formSelector] = theFunction;
};
jQuery.g.formWatcher.prototype.handleForm = function (event) {
    var settings = event.data.self.settings;
    // in IE6 jQuery(event.target) is the button!!! so, we have to use jQuery(this) to find the form:
    var form = jQuery(this);

    if (form.is(settings.validateSelector) && !form.valid()) {
        event.preventDefault();
        form.find('.error:first').focus();
        return;
    }

    if (form.is(settings.confirmSelector)
        && !confirm('Are you sure you want to ' + form.attr('title') + '?')) {
        event.preventDefault();
        return;
    }

    // asynchronously submit if form is requesting it
    if (form.is(settings.asyncSelector)) {
        event.preventDefault();

        // search for any custom functions to execute before submit and execute them here
        if (settings.customBeforeSubmitFunctions) {
            for (var key in settings.customBeforeSubmitFunctions) {
                if (form.is(key)) {
                    // execute the function we found
                    settings.customBeforeSubmitFunctions[key](form);
                    break;
                }
            }
        }

        // default to the main success/error handlers
        var relevantSuccess = settings.commonInstance.defaultSuccess;
        var relevantError = settings.commonInstance.defaultError;

        // optionally, go through the customSuccess functions and see if the form matches any of the selectors
        if (settings.customSuccessFunctions) {
            for (var key in settings.customSuccessFunctions) {
                if (form.is(key)) {
                    // the first match takes precendence, set the relevantSuccess field and go on
                    relevantSuccess = settings.customSuccessFunctions[key];
                    break;
                }
            }
        }
        if (settings.customErrorFunctions) {
            for (var key in settings.customErrorFunctions) {
                if (form.is(key)) {
                    // the first match takes precendence, set the relevantError field and go on
                    relevantError = settings.customErrorFunctions[key];
                    break;
                }
            }
        }

        jQuery.ajax({
            url: form.attr('action'),
            type: form.attr('method'),
            data: form.serialize(),
            success: relevantSuccess,
            global: false,
            error: relevantError
        });
        // need this because of global: false which disables all global ajax hooks
        jQuery.g.common.instance.showLoading();
    }
};
jQuery.g.formWatcher.prototype.setupSaveContainer = function (options) {

    // make all buttons pretty buttons
    jQuery('input.submit').button();

    var settings = jQuery.extend({
        safetyText: 'Safety Check: make sure you want to save all the changes above.',
        buttonText: 'Save'
    }, options);

    jQuery('ul.saveContainer span.safetyText').text(settings.safetyText);
    jQuery('ul.saveContainer input.submit').val(settings.buttonText);

    // set up the safety check on the forms that use the shared SaveContainer view
    this.resetSaveContainers();
    jQuery('ul.saveContainer input.safetyCheck').click(function () {
        var submitContainer = jQuery(this).closest('ul.saveContainer').find('li.submitContainer');
        if (jQuery(this).is(':checked')) {
            submitContainer.show();
        }
        else {
            submitContainer.hide();
        }
    });
};

jQuery.g.formWatcher.prototype.resetSaveContainers = function () {
    jQuery('ul.saveContainer li.submitContainer').hide();
    jQuery('ul.saveContainer input.safetyCheck').attr('checked', false);
};

jQuery.g.formWatcher.prototype.init = function () {
    var self = this;

    jQuery(this.settings.watchOnlyFor).live('submit', { self: this }, this.handleForm);

    // set up the global instance reference to point to this
    jQuery.g.formWatcher.instance = this;

    jQuery('form').ready(function (event) {
        var form = jQuery(this);
        // validate if form is requesting it TODO: not working yet
        if (form.is(self.settings.validateSelector)) {
            var validation = form.validate();
        }
    });
};
/**** end formWatcher ******/
